/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* next;
    Node* random;

    Node(int _val) {
        val = _val;
        next = NULL;
        random = NULL;
    }
};
*/

class Solution {
public:
    Node* copyRandomList(Node* head) {
        map<Node*, Node*> copymap;
        Node* copyhead = nullptr;
        Node* copypre = nullptr;

        Node* cur = head;
        while (cur)
        {
            Node* newnode = new Node(cur->val);
            if (copyhead == nullptr)
            {
                copyhead = copypre = newnode;
            }
            else {
                copypre->next = newnode;
                copypre = copypre->next;

            }
            copymap[cur] = newnode;
            cur = cur->next;
        }

        cur = head;
        copypre = copyhead;
        while (cur)
        {
            if (cur->random == nullptr)
                copypre->random = nullptr;
            else
                copypre->random = copymap[cur->random];
            cur = cur->next;
            copypre = copypre->next;
        }
        return copyhead;
    }
};